<template>
    <Popup
        :show="visible"
        position="bottom"
        teleport="body"
        @close="closeComment"
        :duration="0.25"
    >
        <div class="comment-container">
            <div class="comment-title" v-if="props.showTitle">
                <slot name="title">{{ props.title }}</slot>
            </div>
            <Field
                ref="messageRef"
                class="comment-text"
                v-model="message"
                rows="3"
                type="textarea"
                :maxlength="maxlength"
                :placeholder="selfPlaceholder"
            />
            <div class="comment-image" v-if="fileList.length">
                <Uploader
                    v-show="props.showImage"
                    v-model="fileList"
                    :show-upload="false"
                ></Uploader>
            </div>
            <div class="comment-control">
                <!-- <template v-if="isAndroid">
                    <Icon
                        :size="24"
                        color="#6e7074"
                        name="photo-o"
                        @click="appImageUpload"
                    />
                </template>
                <template v-else>
                    <Uploader
                        v-show="props.showImage"
                        v-model="fileList"
                        multiple
                        :accept="props.accept"
                        :disabled="loading"
                        :preview-image="false"
                        :max-count="props.maxCount"
                        :max-size="props.maxSize"
                        @oversize="onOversize"
                    >
                        <Icon :size="24" color="#6e7074" name="photo-o" />
                    </Uploader>
                </template> -->
                <div class="comment-control-right">
                    <div class="text-number">{{ textNumber }}</div>
                    <Button
                        type="primary"
                        @click="handleSubmit"
                        :loading="loading"
                        >发布</Button
                    >
                </div>
            </div>
        </div>
    </Popup>
</template>
<script setup>
import { Uploader, Button, Field, Icon, Toast, Popup } from 'vant';
import { ref, computed, watch, nextTick } from 'vue';
import createUploader from '@/lib/uploader-client';
import { useStore } from 'vuex';
import envJudge from '@/lib/judge-env';
const env = envJudge();
const isAndroid = ref(['android'].includes(env));

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    showTitle: {
        type: Boolean,
        default: true
    },
    title: {
        type: String,
        default: '发表评论'
    },
    // 默认接受的图片格式
    accept: {
        type: String,
        default: 'image/*'
    },
    placeholder: {
        type: String,
        default: '请输入留言'
    },
    // 回复人名称
    replyName: {
        type: String,
        default: ''
    },
    // 回复的评论id
    replyId: {
        type: String,
        default: undefined
    },
    // 最大字数
    maxlength: {
        type: Number,
        default: 100
    },
    // 点击提交时是否阻止使用组件默认的提交接口
    useDefaultPost: {
        type: Boolean,
        default: false
    },
    // 是否显示添加图片
    showImage: {
        type: Boolean,
        default: false
    },
    // 最大图片张数
    maxCount: {
        type: Number,
        default: 9
    },
    // 图片最大尺寸
    maxSize: {
        type: Number,
        default: 5000 * 1024
    }
});

const emit = defineEmits(['submit', 'update:visible', 'oversize']);

const store = useStore();
const loading = ref(false);
const messageRef = ref();
const message = ref(''); // 文字
const fileList = ref([]); // 图片

const selfPlaceholder = computed(() => {
    if (props.replyName) {
        return `回复${props.replyName}：`;
    } else {
        return `${props.placeholder}`;
    }
});

const textNumber = computed(() => {
    if (message.value) {
        return `${message.value.length}/${props.maxlength}`;
    }
    return `0/${props.maxlength}`;
});

// 关闭弹窗清空内容
watch(
    () => props.visible,
    async (val) => {
        if (!val) {
            message.value = '';
            fileList.value = [];
        } else {
            await nextTick();
            messageRef.value && messageRef.value.focus();
        }
    }
);

// 提交
const handleSubmit = async () => {
    loading.value = true;
    message.value = message.value || '';
    let msgValid = message.value === '' || message.value.trim() === '' || message.value.trim().length < 2
    if (msgValid && fileList.value.length === 0) {
        if (props.showImage) {
            G_dispatchEvent('toast', { message: '请输入评论或上传图片', type: 'error'});
        } else {
            G_dispatchEvent('toast', { message: '请输入正确的评论内容，至少2个字', type: 'error'});
        }
        messageRef.value && messageRef.value.focus();
        loading.value = false;
        return;
    }
    if (!props.showImage) {
        emit('submit', {
            message: message.value
        });
    } else {
        if (isAndroid.value) {
            emit('submit', {
                message: message.value,
                fileList: fileList.value.map((item) => ({
                    materialId: item.materialId,
                    previewUrl: item.url
                }))
            });
        } else {
            const uploadClient = await createUploader();
            const promiseList = fileList.value.map(async (item) => {
                return new Promise((resolve, reject) => {
                    uploadClient.start(item.file, 'image', {
                        onProgress: () => {},
                        onSuccess: ({ data }) => {
                            resolve(
                                store.dispatch('proxyAction', {
                                    name: 'materialPublish',
                                    data: {
                                        materialFullName: data.name,
                                        materialHash: data.hash,
                                        materialSize: data.size,
                                        materialUrl: data.url,
                                        ispType: data.ispType
                                    }
                                })
                            );
                        },
                        onError: (err) => {
                            G_dispatchEvent('toast', {
                                message: `${
                                    err?.info?.desc || err.message || '请求错误'
                                }`,
                                type: 'error'
                            });
                            reject(err);
                        }
                    });
                });
            });
            try {
                const res = await Promise.all(promiseList);
                emit('submit', {
                    message: message.value,
                    fileList: res.map((item) => item.data)
                });
            } catch (error) {
                G_dispatchEvent('toast', { message: error.message, type: 'error'});
            }
        }
    }
    // await submitReply();
    loading.value = false;
};

// 评论接口
const submitReply = async () => {
    if (!props.useDefaultPost) return undefined;
    try {
        // await G_transmit('', {});
    } catch (error) {}
    closeComment();
    loading.value = false;
};

// 图片大小超出范围
const onOversize = (file) => {
    G_dispatchEvent('toast', { message: `文件大小不能超过 ${props.maxSize / 1024}kb`, type: 'error'});
    emit('oversize');
};

// 关闭弹窗
const closeComment = () => {
    emit('update:visible', false);
    message.value = '';
    fileList.value = [];
};

// 安卓系统的图片上传
const appImageUpload = () => {
    store.dispatch('jsBridge/SXYJSBridge', {
        method: 'openAlbum',
        fun: 'album', //  上传类型 album|camera
        data: {
            max: props.maxCount - fileList.value.length
        },
        callback: (data) => {
            fileList.value = [...fileList.value, ...data.materials];
        }
    });
};
</script>
<style lang="scss" scoped>
.comment-container {
    background: #fff;
    padding: 12px 10px;
    width: 100%;
    :deep(.van-field) {
        background-color: #f5f5f5;
        width: 100%;
        height: 90px;
        background: #f5f5f5;
        border-radius: 2px;
        padding: 10px;
        margin-bottom: 12px;
    }
    :deep(.comment-image) {
        overflow: auto;
        .van-uploader__wrapper {
            flex-wrap: nowrap;
            .van-uploader__preview {
                margin: 0 8px 0 0;
                .van-uploader__preview-delete {
                    top: 5px;
                    right: 5px;
                    width: 14px;
                    height: 14px;
                    border-radius: 50%;
                    background: rgba(0, 0, 0, 0.5);
                    .van-uploader__preview-delete-icon {
                        top: 50%;
                        right: 50%;
                        display: block;
                        transform: translate3d(50%, -50%, 0) scale(0.8);
                    }
                }
            }
        }
    }
}
.comment {
    &-title {
        font-size: 15px;
        font-weight: bold;
        color: #171a1d;
        line-height: 24px;
        margin-bottom: 10px;
    }
    &-text {
        font-size: 15px;
        font-weight: 400;
        color: #ed3340;
        line-height: 24px;
    }
    &-image {
        margin-bottom: 12px;
    }
    &-control {
        display: flex;
        align-items: center;
        justify-content: space-between;
        &-right {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            flex: 1;
        }
        .text-number {
            height: 22px;
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #a2a3a4;
            margin-right: 10px;
        }
        button {
            width: 48px;
            height: 28px;
            background: #0084f6;
            border-radius: 2px;
            font-size: 14px;
            font-weight: 400;
            color: #ffffff;
            line-height: 22px;
            padding: 0;
            text-align: center;
        }
    }
}
</style>
